#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/pwm.h"

void fan_control(int fan_control_pin, const int fan_level)
{
    gpio_init(fan_control_pin);
    gpio_set_function(fan_control_pin, GPIO_FUNC_PWM);
    
    uint slice_num = pwm_gpio_to_slice_num(fan_control_pin);
    // printf("slice number is %d\n.", slice_num);
    pwm_set_wrap(slice_num, 255);
    pwm_set_enabled(slice_num, true);
    // pwm_set_chan_level(slice_num, PWM_CHAN_B, fan_level);
	pwm_set_gpio_level(fan_control_pin, fan_level);
}

void get_fan_speed(int fan_pin, float *speed)
{
    if(gpio_get(fan_pin))
    {
        while(gpio_get(fan_pin))
        {
            continue;
        }
        uint32_t t1 = time_us_32();
        while(!gpio_get(fan_pin))
        {
            continue;
        }
        uint32_t t2 = time_us_32();
        uint32_t T = (t2-t1)*2;
	    *speed = 30000000.0/T;
    }
    else
    {
        while(!gpio_get(fan_pin))
        {
            continue;
        }
        uint32_t t1 = time_us_32();
        while(gpio_get(fan_pin))
        {
           continue;
        }
        uint32_t t2 = time_us_32();
        uint32_t T = (t2-t1)*2;
	    *speed = 30000000.0/T;
    }
}
